<template>
  <div>
    李锦鹤
    <el-card>
      <page-tool>
        <div slot="before">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item>
              <el-input placeholder="根据用户名搜索" v-model="dataList.title">
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="onclear">清除</el-button>
              <el-button type="primary" @click="getPowers">搜索</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div slot="after">
          <el-button type="success" icon="el-icon-edit" @click="addPowers">新增权限组</el-button>
        </div>
      </page-tool>
      <el-alert class="el-icon-info" :title="`共${counts}条记录`" type="info" :closable="false">
      </el-alert>
      <!-- 内容展示区 -->
      <el-table :data="list" style="width: 100%" :default-sort="{prop: 'date', order: 'descending'}">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column prop="title" label="用户名" min-width="45%" align="center">
        </el-table-column>
        <el-table-column prop="create_date" label="日期" sortable min-width="45%">
          <template slot-scope="scope">
            {{scope.row.create_date | parseTimeByString("{y}-{m}-{d}")}}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" min-width="10%" align="center">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" circle plain @click="modificationBtn(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" circle plain @click="removeBtn(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" background
        :page-sizes="[5, 10, 20, 50]" layout="prev, pager, next, sizes, jumper" :total="counts"
        :paginationPagesize="list.pagesize" :paginationPage="list.page">
      </el-pagination>
    </el-card>
    <!-- 新增对话框 -->
    <el-dialog title="新建权限组" :visible.sync="addDialogVisible" width="50%">
      <el-form :model="addForm" :rules='addCateFormRures' label-width="80px" class="addDiaForm" ref="addFormRef">
        <el-form-item label="用户名" prop="title">
          <el-input v-model="addForm.title" autocomplete="off" class="tnInput"></el-input>
        </el-form-item>
        <!-- 权限分配 -->
        <el-form-item label="权限分配">
          <el-tree :props="menuprops" show-checkbox :data='menulists' node-key='id' ref="treeRef" default-expand-all>
          </el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCancel">取 消</el-button>
        <el-button type="primary" @click="addBtn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog title="编辑权限组" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="editForm" :rules='addCateFormRures' label-width="80px" class="addDiaForm" ref="editFormRef">
        <el-form-item label="用户名" prop="title">
          <el-input v-model="editForm.title" autocomplete="off" class="tnInput"></el-input>
        </el-form-item>
        <!-- 权限分配 -->
        <el-form-item label="权限分配">
          <el-tree :props="menuprops" show-checkbox :data='menulists' node-key='id' ref="editTreeRef"
            default-expand-all>
          </el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCancel">取 消</el-button>
        <el-button type="primary" @click="editBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { list, remove, add, detail, update } from '@/api/base/permissions.js'
import { list as menulist } from '@/api/base/menus.js'

export default {
  data () {
    return {
      // 权限数据
      list: [],
      dataList: {
        page: 1,
        pagesize: 10,
        keyword: ''
      },
      counts: 0,
      checkedUser: [],
      // 新增对话框的显示与隐藏
      addDialogVisible: false,
      addForm: {
        title: '',
        permissions: ''
      },
      //  添加权限组验证规则
      addCateFormRures: {
        title: [
          { required: true, message: '请输入用户名称', trigger: 'blur' }
        ]
      },
      // 树参数
      props: {
        label: 'list.title',
        children: 'zones'
      },
      // 所有权限
      menulists: [],
      menuprops: {
        label: 'title',
        children: 'childs'
      },
      // 修改对话框的显示与隐藏
      editDialogVisible: false,
      // 修改对话框的参数
      editForm: {
        title: '',
        permissions: ''
      }
    }
  },
  methods: {
    // 获取权限数据
    async getPowers () {
      const { data: res } = await list(this.dataList)
      this.list = res.list
      this.counts = res.counts
    },
    // 监听pagesize改变事件
    handleSizeChange (newSize) {
      this.dataList.pagesize = newSize
      this.getPowers()
    },
    // 监听page改变事件
    handleCurrentChange (newpage) {
      this.dataList.page = newpage
      this.getPowers()
    },
    // 清除按钮
    onclear () {
      this.dataList.title = null
      this.getPowers()
    },
    // 弹出新增对话框
    async addPowers () {
      const { data } = await menulist()
      console.log(data)
      function deepCopy (source) {
        if (typeof source !== 'object') return source
        const target = Array.isArray(source) ? [] : {}
        for (const k in source) {
          if (source.hasOwnProperty(k)) {
            if (k === 'points') {
              target.childs = deepCopy(source[k])
            } else {
              target[k] = deepCopy(source[k])
            }
          }
        }
        return target
      }
      this.menulists = [{ title: '系统菜单和页面权限点', id: 1, childs: deepCopy(data) }]
      // console.log(this.menulists)
      this.addDialogVisible = true
    },
    // 新增对话框取消按钮
    addCancel () {
      this.$refs.addFormRef.resetFields()
      this.addDialogVisible = false
    },
    // 新增对话框确定按钮
    addBtn () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        this.addForm.permissions = this.$refs.treeRef.getCheckedKeys()
        // console.log(this.addForm.permissions)
        if (this.addForm.permissions.length === 0) {
          this.$message.error('请勾选权限')
          return
        }
        try {
          await add(this.addForm)
          this.$message.success('新建权限组成功！')
          // this.$message.success('添加数据成功')
          this.getPowers()
          this.addDialogVisible = false
        } catch (error) {
          // console.log(error)
          this.$message.error('新建权限组失败')
        }
        this.$refs.addFormRef.resetFields()
      })
    },
    // 弹出修改对话框
    async modificationBtn (row) {
      this.editForm.title = row.title
      this.editForm.id = row.id
      const { data } = await menulist()
      // console.log(data)
      function deepCopy (source) {
        if (typeof source !== 'object') return source
        const target = Array.isArray(source) ? [] : {}
        for (const k in source) {
          if (source.hasOwnProperty(k)) {
            if (k === 'points') {
              target.childs = deepCopy(source[k])
            } else {
              target[k] = deepCopy(source[k])
            }
          }
        }
        return target
      }
      this.menulists = [{ title: '系统菜单和页面权限点', id: 1, childs: deepCopy(data) }]
      this.editDialogVisible = true
      const { data: res } = await detail(row)
      console.log(res)
      this.$refs.editTreeRef.setCheckedKeys(res.permissions)
    },
    // 修改对话框的取消按钮
    editCancel () {
      this.$refs.editFormRef.resetFields()
      this.editDialogVisible = false
    },
    // 修改对话框的确定按钮
    async editBtn () {
      // update
      this.editForm.permissions = this.$refs.editTreeRef.getCheckedKeys()
      // console.log(this.editForm.permissions)
      try {
        await update(this.editForm)
        this.$message.success('编辑权限组成功！')
        // this.$message.success('添加数据成功')
        this.getPowers()
        this.editDialogVisible = false
      } catch (error) {
        // console.log(error)
        this.$message.error('编辑权限组失败')
      }
      this.$refs.editFormRef.resetFields()
    },
    // 删除按钮
    removeBtn (id) {
      this.$confirm('此操作将永久删除该标签, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await remove({ id })
          const res = await list(this.dataList)
          if (!res.data.list.length > 0) {
            if (this.dataList.page > 1) {
              this.dataList.page--
            } else if (this.dataList.page === 1) {
              this.dataList.page = 1
            }
          }
          this.getPowers()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch((err) => {
          console.log(err)
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  },
  computed: {},
  watch: {},
  filters: {},
  components: {},
  created () {
    this.getPowers()
  },
  mounted () { }
}
</script>

<style scoped lang='less'>
.el-card {
  border: 1px solid #ebeef5;
  background-color: #fff;
  color: #303133;
  -webkit-transition: 0.3s;
  transition: 0.3s;
  padding-bottom: 12px;
  margin: 10px;
}
.el-alert {
  margin: 14px 0;
}
.el-pagination {
  margin-top: 15px;
  float: right;
}
.tnInput {
  width: 280px;
}
.el-dialog__body {
  padding: 30px 20px;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
}
.addDiaForm {
  margin-left: 150px;
}
</style>
